package net.pws.oos.web.dto;

import net.pws.common.beanutils.BeanUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.oos.biz.model.Organization;
import net.pws.oos.biz.model.User;

import org.apache.commons.lang.StringUtils;

public class UserDto extends User {
    
	private static final long serialVersionUID = 2232074903543933522L;

	public static UserDto from(User user) {
        UserDto result = new UserDto();
        String[] props = {"organization", "roles"};
        BeanUtils.copyProperties(result, user, props);
        Organization organ = user.getOrganization();
        if (null != organ) {
            result.setOrganId(organ.getId());
            result.setOrganName(organ.getName());
        }
        return result;
    }
    
    public static User to(UserDto dto) {
        User user = new User();
        BeanUtils.copyProperties(user, dto);
        if (StringUtils.isEmpty(user.getId())) {
            user.setId(null);
        }
        return user;
    }
    
    public static User to(UserDto dto, EntityManager entityManager) {
        User user = entityManager.find(User.class, dto.getId());
        if(user == null) {
        	user = new User();
        }
        user.setName(dto.getName());
        user.setAccount(dto.getAccount());
        user.setDescription(dto.getDescription());
        user.setWebAccessAllowed(dto.getWebAccessAllowed());
        user.setMobileAccessAllowed(dto.getMobileAccessAllowed());
        user.setMobile(dto.getMobile());
        if (StringUtils.isNotEmpty(dto.getOrganId())) {
            user.setOrganization(entityManager.find(Organization.class,
                                                    dto.getOrganId()));
        }
        if (StringUtils.isBlank(user.getMobile())) {
        	user.setMobile(null);
        }
        return user;
    }
    
    private String organId;
    
    private String organName;
    
    public String getOrganId() {
        return organId;
    }
    
    public void setOrganId(String organId) {
        this.organId = organId;
    }
    
    public String getOrganName() {
        return organName;
    }
    
    public void setOrganName(String organName) {
        this.organName = organName;
    }
    
}
